using System;
using System.Threading;
using BSDS.Core.Infrastructure.Configuration;
using BSDS.Core.Infrastructure.Logging;
using BSDS.Core.Intialization;

namespace BSDS.Core.Infrastructure
{
    internal class NamedMutexHolder : IDisposable
    {
        private Mutex mutex;
        private readonly Logger logger;
        private bool requireExclusiveFolderAccess;

        public NamedMutexHolder(Logger logger, bool requireExclusiveFolderAccess)
        {
            this.logger = logger;
            this.requireExclusiveFolderAccess = requireExclusiveFolderAccess;
        }

        public void Initialize(IBsdsIntializationOptionsProvider optionsProvider)
        {
            bool createdNew;

            if (!requireExclusiveFolderAccess)
                return;

            var mutexName = optionsProvider.MutexName.Replace(':', '-').Replace('\\', '-');
            mutex = new Mutex(true, mutexName, out createdNew);

            if (!createdNew)
            {
               logger.Log("BSDS is already running!");

                throw new ApplicationException("BSDS Instance is already running with id: " + mutexName);
            }
        }

        public void Dispose()
        {
            if(mutex != null)
            {
                mutex.Dispose();
            }
        }
    }
}